// 引入接口文件
// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config';
import { queryAddressList,queryAllAddress,getDetail,timeList,scopeList,queryProductByType,create,update,getDesignatedList,deleteDesignated, createTimeSlot,relieveTimeSlot,updatePublished,designated} from './activityDetailServ'
import AppBus from '../../../../utils/bus'


function includes (item,arr) {
  let flag=false
  if(arr.indexOf(item+'')>-1){
    flag=true
  }
  return flag
}
// 初始默认状态
const defultState = {
  xxx: '1',
  search: '',
  loading: false,
  btnLoading: false,
  publishLoading: false,
  sellType: 1,
  pageType: 'edit',
  previewImage: '',
  id: '1',
  areaList: [],
  //复选框选中商品
  selectedRowKeys:[],
  detailInfo: {},
  // 表格数据
  tableData: {
    dataSource: [

    ],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo:''
  },
  formData: {
    name: '',
    newTime: null,
    imageUrls: [],
    date: [],
  },
  imageUrls: [],
  fileList: [],
  modalObj: {
    selectedRowKeys:[],
    onitem:[],
    visible:false,
    // 表格数据
    tableData: {
      dataSource: [

      ],
      total: 0,
      stop:0,
      start:0
    },
    // 表格数据
    
    // 表格分页设置
    pageConfig: {
      pageSize: Number.parseInt(config.smallPageSizeList[0]),
      pageNo: ''
    },
  },
  tableModalData: {
    dataSource: [

    ],
    total:0,
    stop:0,
    start:0
  },
  onItem:[],
  designatedVisible:false,
  value:'0',
  currentItem:{},
  accountItem:{
    type:'1'
  },
  activityDetail:{},
  addressList:[],
  areaList:[],
  productIds:[],
  detailBanner:'',
  gif:[
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go1.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go2.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go3.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go4.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go5.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go6.png',
  ],   
  visible:false,
  imgStyle:true,
  local:false,
  gifimg:'',
  selectItem:[],
  timeArr:[],
  isSubmit:true,//富文本是否编辑状态
  timerVisible:false,
  date:{},
  timerItem:{}
}

// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query,search }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({ type: 'ifRefresh', payload: {pathname, query,search} });//每次进去页面先重置状态
          dispatch({ type: 'getAreaList', payload: {} });
          dispatch({ type: 'getAddressList', payload: {} })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    //文本编辑内容处理
    * dealEditor({ payload }, { put, select }) {
			let { detailInfo } = yield select(state => state[tmpModule.namespace])
			console.log(detailInfo)
			let newDetail=Object.assign({}, detailInfo)
			newDetail.ruleDesc=payload.ruleDesc
			yield put({ type: 'updateStore', payload: { detailInfo: newDetail } });
		  },
    // 查询记录  详情
    *queryInfo({ payload }, { put, call, select }) {
      let {detailInfo,formData,imageUrls,fileList, detailBanner,gifimg,selectItem,pageType,productIds,id} = yield select(state => state[tmpModule.namespace])
      const {success,msg,data} = yield call(getDetail, {seckillActivityId:payload.id||id, });
      console.log(data);
      if(success){
        //debugger
        detailInfo=data||{}
        formData=data||{}
        productIds = data.productIds
        //selectItem = [{key:data.productIds}]
        imageUrls = data.imageUrls || []
        if(data.detailBanner&&data.detailBanner.indexOf(',')>-1){
          detailBanner = data.detailBanner.split(',')[0]||''
          gifimg = data.detailBanner.split(',')[1] || ''
        }else{
          detailBanner = data.detailBanner
          gifimg = ''
        }
        yield put({type:'scopeList',payload:{seckillActivityId:payload.id,pageSize:productIds.length}})
      }
     // debugger
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          imageUrls,
          fileList,
          detailBanner,
          gifimg,
         //selectItem,
          productIds,
          imgStyle:data.imgStyle==1?false:true,
          ...payload,
        }
      });
    },
    *scopeList({ payload }, { put,call, select }){
      let {selectItem} = yield select(state => state[tmpModule.namespace])
      const {success,msg,rows} = yield call(scopeList, {seckillActivityId:payload.seckillActivityId,pageSize:payload.pageSize,pageNo:1 });
      if(success){
        yield put({
          type: 'updateStore',
          payload: {
           selectItem:rows
          }
        });
      }
    },
    *pageChange({ payload }, { put, select }) {
      const { pageNo, pageSize } = payload;
      const { pageConfig } =yield select(state => state[tmpModule.namespace])
      yield put({ type: 'updateStore', payload: { pageConfig: { ...pageConfig, ...payload } } });
      yield put({ type: 'timeList', payload: { pageNo, pageSize } });
    },

    *pageChangeModal({ payload }, { put, select }) {
      const { pageNo, pageSize } = payload;
      const { modalObj } =yield select(state => state[tmpModule.namespace])
      modalObj.pageConfig= { ...modalObj.pageConfig, ...payload }
      yield put({ type: 'updateStore', payload: { modalObj }});
      yield put({ type: 'queryProductByType', payload: { pageNo, pageSize } });
    },

    //查询操作
    *timeList({ payload = {} }, { call, put, select }) {
      let {queryList,tableData,pageConfig,id,timeArr} = yield select(state => state[tmpModule.namespace])
      let data= yield select(state => state[tmpModule.namespace])
      const pageSize = pageConfig.pageSize;
      //组装接口入参
      let params = {
        seckillActivityId:payload.id||id,
      };
      //显示loading状态
      yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
      const {rows,success,msg,total,pageNo} = yield call(timeList, { ...params, pageNo: payload.pageNo||data.pageNo, pageSize, });
      yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
      // console.log('数据',rows,success,msg,total,pageNo);
      if (success) {
        let list=rows||[]
        list.map((item,index)=>{
          item.key = index+1;
          timeArr = [...timeArr,item.startTime]
        });

        // 时间排序
        timeArr = timeArr.sort(function(a,b){
          return b>a? 1 : -1
        })
        tableData = {
          dataSource: list,
          total:Number(total)
        }
        yield put({
          type: 'updateStore', payload: {
            pageConfig: {...pageConfig, pageNo},timeArr,
            tableData,
            ...payload
          }
        })
      }
    },

    //查询操作
    *queryProductByType({ payload = {} }, { call, put, select }) {
      let {queryList,modalObj,id,formData,sellType} = yield select(state => state[tmpModule.namespace])
      let {tableData,pageConfig}=modalObj
      const  pageSize = pageConfig.pageSize;
      //显示loading状态
      yield put({ type: 'updateStore', payload: { loading: true,btnLoading: true, } })
      // seckillProductIds  startTime endTime seckillActivityId
      //组装接口入参
      let params = {
        sellType,
      };
      const {rows,success,msg,total,pageNo} = yield call(queryProductByType, { ...params, pageNo: payload.pageNo||1, pageSize, });
      // console.log('数据',rows,success,msg,total,pageNo);
      if (success) {
        let list=rows||[]
        list.map((item,index)=>{
          item.key = item.seckillProductId;
        });
        tableData = {
          dataSource: list,
          total:Number(total)
        }
        modalObj.tableData=tableData
        modalObj.pageConfig= {...pageConfig, pageNo},
          yield put({
            type: 'updateStore', payload: {
              loading: false,
              btnLoading: false,
              modalObj
            }
          })
      }
    },
    // 删除
    *relieveTimeSlot({payload }, { put,select,call}) {
      let {id, formData, imageUrls,detailInfo} = yield select(state => state[tmpModule.namespace])
      let ids=[]
      // console.log('relieveTimeSlot',payload)
      let params = {
        seckillProductId:payload.seckillProductId,
      }
      const {success, msg, data} = yield call(relieveTimeSlot, params)
      if (success) {
        message.success('操作成功')
        yield put({type: 'timeList', payload: {formData}})
      }
    },
    // 修改
    *update({payload }, { put,select,call}) {
      let {id, formData, imageUrls,sellType,productIds,detailBanner,gifimg,imgStyle,detailInfo} = yield select(state => state[tmpModule.namespace])
      let ids=[]
      let params = {
        sellType,
        name: formData.name,
        imageUrls: imageUrls,
        seckillActivityId:id,
        productIds,
        detailBanner:`${detailBanner}${!imgStyle&&gifimg.length>0?','+gifimg:''}`,
        imgStyle:imgStyle?2:1,
        ruleDesc:detailInfo.ruleDesc,
        showStartTime:formData.showStartTime,
        showEndTime:formData.showEndTime,
        btnName:formData.btnName
      }
      yield put({ type: 'updateStore', payload: { btnLoading:true } })
      const {success, msg, data} = yield call(update, params)
      yield put({ type: 'updateStore', payload: { btnLoading:false } })
      if(success){
        if(payload.type==2){
          yield put({ type: 'updatePublished', payload: { newType:payload.type  } });
        }else{
          message.success('操作成功',1,() => {
            // yield put({type: 'queryInfo', payload: {}})
            let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
            // console.log('urlArray', urlArray)
            AppBus.emit('closeTab', {
              key: urlArray[0],
              cbf: () => {
                hashHistory.push(urlArray[1])
                payload.resetFields()
              }
            })
          })
        }
      }
    },
    // 新增
    * create ({payload}, {put, select, call}) {
      let {id, formData, imageUrls,sellType,productIds,detailBanner,gifimg,imgStyle,detailInfo} = yield select(state => state[tmpModule.namespace])
      let params = {
        sellType,
        name: formData.name,
        imageUrls: imageUrls,
        productIds,
        detailBanner:`${detailBanner}${gifimg.length>0?','+gifimg:''}`,
        imgStyle:imgStyle?2:1,
        ruleDesc:detailInfo.ruleDesc,
        showStartTime:formData.showStartTime,
        showEndTime:formData.showEndTime,
        btnName:formData.btnName
      }
      yield put({ type: 'updateStore', payload: { btnLoading:true } })
      const {success, msg, data} = yield call(create, params)
      yield put({ type: 'updateStore', payload: { btnLoading:false } })
      if(success){
        yield put({ type: 'updateStore', payload: { pageType:'edit' } })
        message.success('操作成功',1,()=> {
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          hashHistory.push({
            pathname: urlArray[0],
            query: { id: data.seckillActivityId||'',pageType:'edit'}
          })
        })
      }
    },
    // 发布、撤销 发布状态	published（1，未发布。2，已发布，3已撤销）
    * updatePublished ({payload}, {put, select, call}) {
      let {id, formData, imageUrls,sellType,timeArr,pageType} = yield select(state => state[tmpModule.namespace])
      let newType=payload.newType
      let params = {
        sellType,
        seckillActivityId: id,
        published: newType,
      }
      yield put({ type: 'updateStore', payload: { publishLoading:true } })
      
      const {success, msg, data} = yield call(updatePublished, params)
      if(success){
        message.success('操作成功')
        let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
        hashHistory.push({
          pathname: urlArray[0],
          query: { id,pageType}
        })
        yield put({type: 'queryInfo', payload: {id}})
      }
      yield put({ type: 'updateStore', payload: { publishLoading:false } })
    },

    // 关联时间段
    * createTimeSlot ({payload}, {put, select, call}) {
      let {id, formData, imageUrls,modalObj,sellType,date} = yield select(state => state[tmpModule.namespace])
      let params = {};
      if(payload.onItem){
        let seckillProductList=[]
        let {onItem=[]}=payload
        let {newTime=[]}=formData
        if(!isEmpty(newTime)){
          newTime=[moment(newTime[0]).format('YYYY-MM-DD HH:mm'),moment(newTime[1]).format('YYYY-MM-DD HH:mm')]
        }
        onItem.map((item,index)=>{
          let seckillMap = {
            productId:item.seckillProductId,
            receiveWay:item.receiveWay
          };
          seckillProductList.push(seckillMap)
        })
        params = {
          sellType,
          seckillActivityId:id,
          startTime:newTime[0],
          endTime:newTime[1],
          seckillProductList:seckillProductList
        };
      }else{
        params = payload.params;
      }
      const {success, msg, data} = yield call(createTimeSlot, params)
      if (success) {
        message.success('操作成功')
        let id = data.seckillActivityId || ''
        yield put({type: 'timeList', payload: {formData}})
      }
    },

    * selectedKeysChange ({payload}, {put, select, call}) {
      let {modalObj} = yield select(state => state[tmpModule.namespace])
      // selectedRowKeys
      // console.log('selectedKeysChange',payload)
      modalObj.selectedRowKeys=payload.selectedRowKeys
      yield put({
        type: 'updateStore',
        payload: {
          modalObj
        }
      })
    },
    * ifRefresh ({payload}, {put, select, call}) {
      let state = yield select(state => state[tmpModule.namespace])
      let {search='',query={}}=payload
      if(state.search.trim()==search.trim()){
        yield put({ type: 'updateStore', payload: { ...query,search} });//每次进去页面先重置状态
      }else{
        yield put({ type: 'updateStore', payload: {...cloneDeep(defultState), ...query,search} });//每次进去页面先重置状态
        if(query.pageType=='add'){
        }else{
          yield put({
            type: 'queryInfo',
            payload: {
              pageType:query.pageType,
              id:query.id,
            }
          })
          yield put({
            type: 'timeList',
            payload: {
              pageType:query.pageType,
              id:query.id,
            }
          })
        }
      }
      return state
    },
    *designated ({payload}, {put, select, call}) {
      let {accountItem,currentItem} = yield select(state => state[tmpModule.namespace])
      console.log(currentItem)
      const {success, msg, data} = yield call(designated,{...accountItem,seckillProductId:currentItem.seckillProductId})
      if(success){
        message.success('更改成功')
        yield put({ type: 'getDesignatedList', payload: {} });
      }
    },
    *getDesignatedList ({payload}, {put, select, call}) {
      let {currentItem,tableModalData} = yield select(state => state[tmpModule.namespace])
      //console.log(currentItem)
      const {success, msg, data={}} = yield call(getDesignatedList,{seckillProductId:currentItem.seckillProductId})
      if(success){
        let dataSource = data.seckillAppointId?[data]:[]
        tableModalData = {
          dataSource,
          total:dataSource.length>0?1:0
        }
        yield put({ type: 'updateStore', payload: {
          tableModalData,
          activityDetail:data
        } });

      }
    },
    *deleteDesignated ({payload}, {put, select, call}) {
      console.log(payload)
      const {success, msg, data} = yield call(deleteDesignated,{seckillAppointId:payload.seckillAppointId})
      if(success){
        message.success('更改成功')
        yield put({ type: 'getDesignatedList', payload: {} });
      }
    },
    // 获取区域地址
    *getAddressList({ payload }, { put, call, select }) {
      let {modalObj,} = yield select(state => state[tmpModule.namespace])
      try {
        // debugger
        const { success, data=[] } = yield call(queryAddressList,{})
        
        if (success) {
          let addressList = []
          data.map((item,index)=>{
            addressList.push({
                id: item.regionId,
                name: item.regionName
              })
          })
          yield put({ type: 'updateStore', payload: { addressList } });
        }
      } catch (e) {
      }
    },
    * getAreaList ({payload}, {put, call, select}) {
      try {
        const data = yield call(queryAllAddress, {})
        if (data.success) {
          let areaList = []
          //澳门与北京只有两级
          let arr = [data.data[0]]
          let attr = [data.data[data.data.length - 1]]
          data.data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          data.data[data.data.length - 1] = {
            label: '澳门',
            value: '820000',
            children: attr
          }
          areaList = data.data
          
          yield put({type: 'updateStore', payload: {areaList}})
        }
      } catch (e) {
      
      }
    },
  },
  
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
